﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;
using System.ServiceModel.Description;

namespace DBServerLibrary.wcf
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
    class WcfDBServer : IDBServer
    {
        private ServiceHost DBServerHost;

        /// <summary>
        /// 开始WCF服务
        /// </summary>
        /// <param name="WcfUrl"></param>
        /// <returns></returns>
        public bool StartServer(string WcfUrl)
        {
            EndServer();

            Uri baseAddress = new Uri(WcfUrl);

            DBServerHost = new ServiceHost(this, baseAddress);

            try
            {
                //采用Windows身份认证
                //WSHttpBinding myBinding = new WSHttpBinding(SecurityMode.Message);
                //myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                //myBinding.Security.Mode = SecurityMode.Message;
                //myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
                BasicHttpBinding myBinding = new BasicHttpBinding();
                DBServerHost.AddServiceEndpoint(
                    typeof(IDBServer),
                    myBinding,//new WSHttpBinding(),
                    "DBServer");

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;

                DBServerHost.Description.Behaviors.Add(smb);

                DBServerHost.Open();

                return true;

            }
            catch (System.ServiceModel.CommunicationException ce)
            {
                DBServerHost.Abort();
                return false;
            }
        }

        /// <summary>
        /// 终止WCF服务
        /// </summary>
        private void EndServer()
        {
            if (DBServerHost != null && DBServerHost.State == CommunicationState.Opened)
            {
                DBServerHost.Close();
                DBServerHost.Abort();
            }
            DBServerHost = null;
        }

       
        #region IDBServer 成员

        public int GetDBServerStatus()
        {
            Random dd = new Random();
            return dd.Next(9999);
        }

        #endregion
    }
}
